package com.dandelion.common.service;

import com.dandelion.common.utils.MaskUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class AddressBuilder {
    private Map<String, String> codeAndNameMap;
    private StringBuilder builder = new StringBuilder(64);

    private AddressBuilder() {
    }

    public static AddressBuilder newBuilder() {
        return new AddressBuilder();
    }

    public AddressBuilder codeAndNameMap(Map<String, String> codeAndNameMap) {
        this.codeAndNameMap = codeAndNameMap;
        if (this.codeAndNameMap == null) {
            this.codeAndNameMap = new HashMap<>();
        }
        return this;
    }

    public AddressBuilder city(String cityCode) {
        return mapToName(cityCode);
    }

    public AddressBuilder prov(String provinceCode) {
        return mapToName(provinceCode);
    }

    public AddressBuilder area(String areaCode) {
        return mapToName(areaCode);
    }

    public AddressBuilder district(String distCode) {
        return mapToName(distCode);
    }

    public AddressBuilder detail(String detail) {
        if (detail != null) {
            builder.append(detail);
        }
        return this;
    }

    public String toString() {
        return builder.toString();
    }

    public String build() {
        return builder.toString();
    }

    public AddressBuilder maskDistrict(String district) {
        builder.append(MaskUtils.maskDistrict(district));
        return this;
    }

    private AddressBuilder mapToName(String code) {
        if (StringUtils.isNotBlank(code)) {
            String value = codeAndNameMap.get(code);
            if (value != null) {
                builder.append(value);
            }
        }
        return this;
    }
}
